package controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.Model;
import databean.User;

public class Controller extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public void init() throws ServletException {


		Model model = new Model(getServletConfig());

		// User
		Action.add(new UserLoginAction(model));
		Action.add(new UserViewEmailsAction(model));
		Action.add(new UserLogoutAction(model));
		Action.add(new HomeAction(model));
		Action.add(new ContactsAction(model));
		Action.add(new ContactsAddAction(model));
		Action.add(new ConversationFeedAction(model));
		Action.add(new ConversationDetailsAction(model));
		Action.add(new ConversationMapAction(model));
		Action.add(new NotesAddAction(model));
	    Action.add(new ReplyAction(model));
	    
		Action.add(new ProductsAddAction(model));
		Action.add(new TasksAddAction(model));
		Action.add(new FoliosAddAction(model));
		Action.add(new NetworksAddAction(model));

		Action.add(new ProductsAction(model));
		Action.add(new NotesAction(model));
		Action.add(new TasksAction(model));
		Action.add(new FoliosAction(model));
		Action.add(new NetworksAction(model));

		Action.add(new TasksViewCreationListAction(model));
		
		
		
		
		Action.add(new TasksEditAction(model));
		Action.add(new ProductsEditAction(model));
		Action.add(new FoliosEditAction(model));
		Action.add(new NetworksEditAction(model));
		Action.add(new FoliosViewDetailsAction(model));
		
		Action.add(new NetworksViewDetailsAction(model));
		
		Action.add(new UserViewProfileAction(model));
		Action.add(new UserEditProfileAction(model));
		Action.add(new GetContactsXMLAction(model));
		Action.add(new UploadEmailXMLAction(model));

		Action.add(new UserViewEmailsInThreadAction(model));
		Action.add(new GetEmailsByConversationID(model));
		Action.add(new VideoAction(model));
		Action.add(new VideoCreateConfAction(model));
		Action.add(new VideoExistingConfsAction(model));
		Action.add(new VideoViewConfAction(model));
		Action.add(new VideoSaveConfNotesAction(model));
		Action.add(new VideoChatroomsAction(model));

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String nextPage = performTheAction(request, response);
		sendToNextPage(nextPage, request, response);
	}

	/*
	 * Extracts the requested action and (depending on whether the user is
	 * logged in) perform it (or make the user login).
	 * 
	 * @param request
	 * 
	 * @return the next page (the view)
	 */
	private String performTheAction(HttpServletRequest request,
			HttpServletResponse response) {
		HttpSession session = request.getSession(true);
		String servletPath = request.getServletPath();
		User user = (User) session.getAttribute("user");
		String action = getActionName(servletPath);

		if ((action.startsWith("user")) && (user == null)) {
			// If the user hasn't logged in, direct him to the login page
			return Action.perform("user-login.do", request, response);
		}


		// Let the logged in user run his chosen action
		return Action.perform(action, request, response);
	}

	/*
	 * If nextPage is null, send back 404 If nextPage starts with a '/',
	 * redirect to this page. In this case, the page must be the whole servlet
	 * path including the webapp name Otherwise dispatch to the page (the view)
	 * This is the common case Note: If nextPage equals "image", we will
	 * dispatch to /image. In the web.xml file, "/image" is mapped to the
	 * ImageServlet will which return the image bytes for display.
	 */
	private void sendToNextPage(String nextPage, HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {

		if (nextPage == null) {
			response.sendError(HttpServletResponse.SC_NOT_FOUND,
					request.getServletPath());
			return;
		}

		if (nextPage.charAt(0) == '/') {
			String host = request.getServerName();
			String port = ":" + String.valueOf(request.getServerPort());
			if (port.equals(":80"))
				port = "";
			response.sendRedirect("http://" + host + port + nextPage);
			return;
		}

		RequestDispatcher d = request.getRequestDispatcher("/WEB-INF/view/"	+ nextPage);
		d.forward(request, response);
	}

	/*
	 * Returns the path component after the last slash removing any "extension"
	 * if present.
	 */
	private String getActionName(String path) {
		// We're guaranteed that the path will start with a slash
		int slash = path.lastIndexOf('/');
		return path.substring(slash + 1);
	}
}
